package com.example.choupaiapp.main.activity.mine;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.common.view.XListView;
import com.example.choupaiapp.main.activity.find.FindBannerWebviewActivity;
import com.example.choupaiapp.main.bean.InviteListBean;
import com.example.choupaiapp.main.bean.InviteStateUserInfoBean;
import com.example.choupaiapp.main.bean.InviteTopBean;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.callback.WechatCallBack;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.util.WXShareUtil;
import com.example.choupaiapp.main.util.WechatLoginUtil;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2020/4/21.
 */

public class InviteNewActivity extends CommonActivity implements OnRefreshLoadMoreListener, WbShareCallback, WechatCallBack {

    @BindView(R.id.invite_code)
    TextView inviteCodeTv;
    @BindView(R.id.description)
    TextView description;
    @BindView(R.id.listview)
    XListView listview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private int pageNum = 1;
    private int pageSize = 20;
    private QuickAdapter<InviteListBean.PageBean.ListBean> quickAdapter;
    private InviteTopBean mInviteTopBean;
    private Tencent mTencent;
    private String inviteCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_new);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            inviteCode = bundle.getString("inviteCode");
            inviteCodeTv.setText(inviteCode);
        }

        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));

        quickAdapter = new QuickAdapter<InviteListBean.PageBean.ListBean>(context, R.layout.item_invite) {
            @Override
            protected void convert(BaseAdapterHelper helper, InviteListBean.PageBean.ListBean item) {
                helper.setText(R.id.phone, item.getMobile().substring(0, 3) + "****" + item.getMobile().substring(7, 11));
                helper.setText(R.id.time, item.getCreateTime());
                TextView state = helper.getView(R.id.state);
                if (item.getInviteStatus() == 1) {
                    state.setText("审核成功");
                } else if (item.getInviteStatus() == 2) {
                    state.setText("等待审核");
                } else if (item.getInviteStatus() == 3) {
                    state.setText("等待发布");
                } else if (item.getInviteStatus() == 4) {
                    state.setText("审核成功");
                }
            }
        };
        listview.setAdapter(quickAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                HttpParams params = new HttpParams();
                params.put("inviteUserId", quickAdapter.getItem(i).getUserId());
                finalOkGo.requestHead(RequestType.POSTHEAD, Url.INVITE_USER_INFO, params, Url.INVITE_USER_INFO, new Callback<InviteStateUserInfoBean>() {
                    @Override
                    public void onSuccess(InviteStateUserInfoBean inviteStateUserInfoBean) {
                        if (inviteStateUserInfoBean.getCode() == Contacts.SUCCESS) {
                            DialogUtil.getInstance().showCenterDialog(context, R.layout.dialog_invite_progress);
                            LinearLayout dialog_invite_progress = (LinearLayout) DialogUtil.getInstance().dialog_center_layout;
                            View point = dialog_invite_progress.findViewById(R.id.point);
                            View point1 = dialog_invite_progress.findViewById(R.id.point1);
                            View point2 = dialog_invite_progress.findViewById(R.id.point2);
                            TextView text = dialog_invite_progress.findViewById(R.id.text);
                            TextView text1 = dialog_invite_progress.findViewById(R.id.text1);
                            TextView text2 = dialog_invite_progress.findViewById(R.id.text2);
                            TextView time = dialog_invite_progress.findViewById(R.id.time);
                            TextView time1 = dialog_invite_progress.findViewById(R.id.time1);
                            TextView time2 = dialog_invite_progress.findViewById(R.id.time2);
                            TextView textview1 = dialog_invite_progress.findViewById(R.id.textview1);
                            TextView textview2 = dialog_invite_progress.findViewById(R.id.textview2);
                            ImageView image1 = dialog_invite_progress.findViewById(R.id.image1);

                            if (inviteStateUserInfoBean.getUser().getInviteStatus() == 1) {
                                //审核成功
                                point.setBackgroundResource(R.drawable.shape_green_oval_invite);
                                point1.setBackgroundResource(R.drawable.shape_green_oval_invite);
                                point2.setBackgroundResource(R.drawable.shape_green_oval_invite);
                                text.setTextColor(getResources().getColor(R.color.color_333));
                                text1.setTextColor(getResources().getColor(R.color.color_333));
                                text2.setTextColor(getResources().getColor(R.color.color_333));
                                textview1.setText(inviteStateUserInfoBean.getAwaitPublish());
                                textview2.setText(inviteStateUserInfoBean.getAwaitAudit());
                                time.setText(inviteStateUserInfoBean.getUser().getCreateTime());
                                time1.setText(inviteStateUserInfoBean.getContent().getCreateTime());
                                time2.setText(inviteStateUserInfoBean.getContent().getAuditTime());

                                textview1.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (Utils.isDoubleClick()) {
                                            return;
                                        }
                                        Bundle bundle = new Bundle();
                                        bundle.putString("url", inviteStateUserInfoBean.getCsaeUrl());
                                        startActivity(FindBannerWebviewActivity.class, bundle);
                                    }
                                });
                            } else if (inviteStateUserInfoBean.getUser().getInviteStatus() == 2) {
                                //等待审核
                                point.setBackgroundResource(R.drawable.shape_green_oval_invite);
                                point1.setBackgroundResource(R.drawable.shape_green_oval_invite);
                                point2.setBackgroundResource(R.drawable.shape_gray_oval_invite);
                                text.setTextColor(getResources().getColor(R.color.color_333));
                                text1.setTextColor(getResources().getColor(R.color.color_333));
                                text2.setTextColor(getResources().getColor(R.color.color_9999));
                                textview1.setText(inviteStateUserInfoBean.getAwaitPublish());
                                textview2.setText(inviteStateUserInfoBean.getAwaitAudit());
                                time.setText(inviteStateUserInfoBean.getUser().getCreateTime());
                                time1.setText(inviteStateUserInfoBean.getContent().getCreateTime());
                                time2.setText("");

                                textview1.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (Utils.isDoubleClick()) {
                                            return;
                                        }
                                        Bundle bundle = new Bundle();
                                        bundle.putString("url", inviteStateUserInfoBean.getCsaeUrl());
                                        startActivity(FindBannerWebviewActivity.class, bundle);
                                    }
                                });
                            } else if (inviteStateUserInfoBean.getUser().getInviteStatus() == 3) {
                                //等待发布
                                point.setBackgroundResource(R.drawable.shape_green_oval_invite);
                                point1.setBackgroundResource(R.drawable.shape_gray_oval_invite);
                                point2.setBackgroundResource(R.drawable.shape_gray_oval_invite);
                                text.setTextColor(getResources().getColor(R.color.color_333));
                                text1.setTextColor(getResources().getColor(R.color.color_9999));
                                text2.setTextColor(getResources().getColor(R.color.color_9999));
                                textview1.setText(inviteStateUserInfoBean.getAwaitPublish());
                                textview2.setText(inviteStateUserInfoBean.getAwaitAudit());
                                time.setText(inviteStateUserInfoBean.getUser().getCreateTime());
                                time1.setText("");
                                time2.setText("");

                                textview1.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (Utils.isDoubleClick()) {
                                            return;
                                        }
                                        Bundle bundle = new Bundle();
                                        bundle.putString("url", inviteStateUserInfoBean.getCsaeUrl());
                                        startActivity(FindBannerWebviewActivity.class, bundle);
                                    }
                                });
                            } else if (inviteStateUserInfoBean.getUser().getInviteStatus() == 4) {
                                //老用户
                                point.setBackgroundResource(R.drawable.shape_green_oval_invite);
                                point1.setBackgroundResource(R.drawable.shape_green_oval_invite);
                                point2.setBackgroundResource(R.drawable.shape_green_oval_invite);
                                text.setTextColor(getResources().getColor(R.color.color_333));
                                text1.setTextColor(getResources().getColor(R.color.color_333));
                                text2.setTextColor(getResources().getColor(R.color.color_333));
                                image1.setVisibility(View.INVISIBLE);
                                textview1.setText("");
                                textview2.setText("");
                                time.setText("");
                                time1.setText("");
                                time2.setText("");
                            }
                        } else {
                            showImageToas(inviteStateUserInfoBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });

            }
        });

        listview.setFocusable(false);
    }

    @Override
    protected void initData() {
        showDialog(context, null);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.INVITE_TOP_INFO, null, Url.INVITE_TOP_INFO, new Callback<InviteTopBean>() {
            @Override
            public void onSuccess(InviteTopBean inviteTopBean) {
                dismissDialog();
                if (inviteTopBean.getCode() == Contacts.SUCCESS) {
                    mInviteTopBean = inviteTopBean;
                    inviteCodeTv.setText(inviteTopBean.getInviteCode());
                    HttpParams params = new HttpParams();
                    params.put("limit", pageSize);
                    params.put("page", pageNum++);
                    finalOkGo.requestHead(RequestType.POSTHEAD, Url.INVITE_LIST, params, Url.INVITE_LIST, new Callback<InviteListBean>() {
                        @Override
                        public void onSuccess(InviteListBean inviteListBean) {
                            if (inviteListBean.getCode() == Contacts.SUCCESS) {
                                description.setText("累计邀请" + inviteListBean.getPage().getTotalCount() + "人，共获得" + inviteTopBean.getSumInvite().stripTrailingZeros().toPlainString() + "元奖励");
                                if (pageNum - 1 == 1) {
                                    quickAdapter.clear();
                                    quickAdapter.addAll(inviteListBean.getPage().getList());
                                } else {
                                    quickAdapter.addAll(inviteListBean.getPage().getList());
                                }
                                refreshLayout.finishRefresh();
                                refreshLayout.finishLoadMore();
                                quickAdapter.notifyDataSetChanged();

                                int pagecount;
                                if (inviteListBean.getPage().getTotalCount() % pageSize == 0) {
                                    pagecount = inviteListBean.getPage().getTotalCount() / pageSize;
                                } else {
                                    pagecount = inviteListBean.getPage().getTotalCount() / pageSize + 1;
                                }

                                if (pageNum > pagecount) {
                                    refreshLayout.setNoMoreData(true);
                                    refreshLayout.finishLoadMoreWithNoMoreData();
                                } else {
                                    refreshLayout.setNoMoreData(false);
                                }
                            } else {
                                refreshLayout.finishRefresh();
                                refreshLayout.finishLoadMore();
                                if (inviteListBean.getCode() == Contacts.TOKEN_EMPTY) {
                                } else {
                                    showImageToas(inviteListBean.getMsg());
                                }
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                        }
                    });
                } else {
                    if (inviteTopBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(inviteTopBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });

    }


    @OnClick({R.id.invite, R.id.copy, R.id.right_img, R.id.rule})
    public void onViewClicked(View view) {
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.invite:
                if (!TextUtils.isEmpty(inviteCode)) {
                } else {
                    UserInfoBean mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");
                    inviteCode = mUserInfoBean.getUser().getInviteCode();
                }
                if (mInviteTopBean != null) {
                    showShareDialog(mInviteTopBean.getInviteUrl() + "?inviteCode=" + inviteCode);
                }
                break;
            case R.id.copy:
                if (!TextUtils.isEmpty(inviteCode)) {
                } else {
                    UserInfoBean mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");
                    inviteCode = mUserInfoBean.getUser().getInviteCode();
                }
                ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
                ClipData clipData = ClipData.newPlainText(null, inviteCode);
                // 把数据集设置（复制）到剪贴板
                clipboard.setPrimaryClip(clipData);
                showToast("邀请码已复制");
                break;
            case R.id.right_img:
                if (mInviteTopBean != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("title", "邀请规则");
                    bundle.putString("url", mInviteTopBean.getInviteRuleUrl());
                    startActivity(RuleWebviewActivity.class, bundle);
                }
                break;
            case R.id.rule:
                if (mInviteTopBean != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("title", "邀请规则");
                    bundle.putString("url", mInviteTopBean.getInviteRuleUrl());
                    startActivity(RuleWebviewActivity.class, bundle);
                }
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        initData();
    }

    private void showShareDialog(String url) {

        DialogUtil.getInstance().showBottomDialog(context, R.layout.dialog_share);
        LinearLayout dialog_share = (LinearLayout) DialogUtil.getInstance().dialog_bottom_layout;
        dialog_share.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                DialogUtil.getInstance().dialog_bottom.dismiss();
            }
        });

        dialog_share.findViewById(R.id.share_wechat).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            WXShareUtil wxShareUtil = new WXShareUtil(context);
            wxShareUtil.registerWx();
            WechatLoginUtil.getInstance().setWechatCallBack(InviteNewActivity.this);

            wxShareUtil.share(url,
                    mInviteTopBean.getInviteTitle(),
                    mInviteTopBean.getInviteDetails(),
                    "", wxShareUtil.SHARETOFRIEND);
            MobclickAgent.onEvent(ContextUtil.getContext(), "invitationID");
        });

        dialog_share.findViewById(R.id.share_wechat_friend).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            WXShareUtil wxShareUtil = new WXShareUtil(context);
            wxShareUtil.registerWx();
            WechatLoginUtil.getInstance().setWechatCallBack(InviteNewActivity.this);
            wxShareUtil.share(url,
                    mInviteTopBean.getInviteTitle(),
                    mInviteTopBean.getInviteDetails(),
                    "", wxShareUtil.SHARETOPYQ);
            MobclickAgent.onEvent(ContextUtil.getContext(), "invitationID");
        });

        dialog_share.findViewById(R.id.share_qq).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            mTencent = Tencent.createInstance(Config.QQ_APP_ID, ContextUtil.getContext());
            Bundle params = new Bundle();
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, mInviteTopBean.getInviteTitle());
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, mInviteTopBean.getInviteDetails());
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);
            mTencent.shareToQQ(InviteNewActivity.this, params, new BaseUiListener());
            shareSuccess();
        });

        dialog_share.findViewById(R.id.share_qq_space).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            mTencent = Tencent.createInstance(Config.QQ_APP_ID, context);
            Bundle params = new Bundle();
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, mInviteTopBean.getInviteTitle() + "\n" + mInviteTopBean.getInviteDetails());//选填
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, "");
            params.putString(QzoneShare.SHARE_TO_QQ_IMAGE_URL, "");
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, url);
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, new ArrayList<String>());
            mTencent.shareToQzone(InviteNewActivity.this, params, new BaseUiListener());
            shareSuccess();
        });

        dialog_share.findViewById(R.id.share_weibo).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            WbSdk.install(ContextUtil.getContext(), new AuthInfo(ContextUtil.getContext(), Config.SINA_APP_KEY, Config.REDIRECT_URL, ""));
            WbShareHandler shareHandler = new WbShareHandler(InviteNewActivity.this);
            shareHandler.registerApp();
            WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
            weiboMessage.textObject = getTextObj(url, mInviteTopBean.getInviteTitle() + "\n" + mInviteTopBean.getInviteDetails());
            shareHandler.shareMessage(weiboMessage, false);
            shareSuccess();
        });

        dialog_share.findViewById(R.id.copy_link).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
            ClipData clipData = ClipData.newPlainText(null, url);
            // 把数据集设置（复制）到剪贴板
            clipboard.setPrimaryClip(clipData);
            showToast("链接已复制");
            MobclickAgent.onEvent(ContextUtil.getContext(), "invitationID");
        });

        dialog_share.findViewById(R.id.copy_text).setVisibility(View.INVISIBLE);

        dialog_share.findViewById(R.id.black_list).setVisibility(View.INVISIBLE);
        dialog_share.findViewById(R.id.report).setVisibility(View.INVISIBLE);

    }

    private void shareSuccess() {
        MobclickAgent.onEvent(ContextUtil.getContext(), "invitationID");
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.SHARE_FRIEND_SUCCESS, null, Url.SHARE_FRIEND_SUCCESS, new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {

                } else {
                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(sendCodeBean.getMsg());
                    }
                }
            }
        });
    }

    @Override
    public void onWbShareSuccess() {
//        showToast("分享成功");
    }

    @Override
    public void onWbShareCancel() {
//        showImageToas("分享取消");
    }

    @Override
    public void onWbShareFail() {
//        showImageToas("分享失败");
    }

    @Override
    public void callBack(BaseResp baseResp) {
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                showToast("分享成功");
                shareSuccess();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                showImageToas("分享取消");
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                showImageToas("分享被拒绝");
                break;
            default:
                showImageToas("分享返回");
                break;
        }
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object o) {
//            showToast("分享成功");
        }

        @Override
        public void onError(UiError uiError) {
//            showImageToas("分享失败");
        }

        @Override
        public void onCancel() {
//            showImageToas("分享取消");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mTencent != null) {
            mTencent.onActivityResult(requestCode, resultCode, data);
        }
    }


    private TextObject getTextObj(String url, String title) {
        TextObject textObject = new TextObject();
        textObject.text = title + "\n" + url;
        textObject.title = title;
        textObject.actionUrl = url;
        return textObject;
    }
}
